package com.ld.shieldsb.common.web.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.ld.shieldsb.common.core.util.SimplePathMatcher;

import lombok.extern.slf4j.Slf4j;

/**
 * 参数去空格过滤器
 * 
 * @author <a href="mailto:donggongai@126.com" target="_blank">吕凯</a>
 * @date 2020年7月7日 下午2:21:35
 *
 */
@Slf4j
public class ParamTrimFilter implements Filter {

    FilterConfig filterConfig = null;

    private List<String> urlExclusion = null; // 排除不过滤的的url
    protected SimplePathMatcher matcherSimple = new SimplePathMatcher(); // 简单过滤器
    private String ignoreNameRegex = ""; // 不处理的字段的name名称的正则表达式

    public ParamTrimFilter() {
        super();
    }

    public ParamTrimFilter(String ignoreNameRegex) {
        super();
        this.ignoreNameRegex = ignoreNameRegex;
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    public void destroy() {
        this.filterConfig = null;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String servletPath = httpServletRequest.getServletPath();

        if (urlExclusion != null && isExclusion(servletPath)) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(new ParamTrimRequestWrapper((HttpServletRequest) request, ignoreNameRegex), response);
        }
    }

    public boolean isExclusion(String requestURI) {
        if (urlExclusion == null || requestURI == null) {
            return false;
        }
        for (String pattern : urlExclusion) {
            if (matcherSimple.matches(pattern, requestURI)) {
                log.warn("参数去前后空格过滤器排除：" + requestURI);
                return true;
            }
        }

        return false;
    }

    public List<String> getUrlExclusion() {
        return urlExclusion;
    }

    public void setUrlExclusion(List<String> urlExclusion) {
        this.urlExclusion = urlExclusion;
    }

    public String getIgnoreNameRegex() {
        return ignoreNameRegex;
    }

    public void setIgnoreNameRegex(String ignoreNameRegex) {
        this.ignoreNameRegex = ignoreNameRegex;
    }

}